const AJAX = getApp().ajax,
      $wx = getApp().$wx,
      getColor = getApp().globalData.getColor;

Page({
  data: {
    scanRecordParams: {
      p: 1,
      num: 20,
      name: ''
    },
    scanRecordTotalPage: 0,
    scanRecord: [],
    noRecord: false
  },

  onLoad(options){
    console.log(options);
    let td = this.data;
    $wx.setNavColor(getColor().val);
    this.getScanKey(td.scanRecordParams);
  },

  onShareAppMessage(){
  
  },

  // 搜索
  search(e){
    let td = this.data, ed = e.detail;
    td.scanRecordParams.p = 1;
    td.scanRecordParams.name = ed.value.search;
    this.getScanKey(td.scanRecordParams);
  },

  // 搜索
  keydownSearch(e){
    let td = this.data, ed = e.detail;
    td.scanRecordParams.p = 1;
    td.scanRecordParams.name = ed.value;
    this.getScanKey(td.scanRecordParams);
  },
  
  // 上拉加载更多
  recordTolower(){
    let td = this.data;

    if (td.scanRecordParams.p < td.scanRecordTotalPage){
      td.scanRecordParams.p ++;
      this.getScanKey(td.scanRecordParams, true);
    }
  },

  // 获取扫码记录
  getScanRecord(e) {
    let td = this.data, scan_record_key = e.currentTarget.dataset.key;
    let key = wx.getStorageSync('sceneInfo').key;

    if (key !== scan_record_key) {
     wx.showModal({
       title: '提示',
       content: '确定选择当前店铺吗',
       success(res){
         if(res.confirm){
           wx.setStorageSync('sceneInfo', { key: scan_record_key });

           setTimeout(callback => {
             wx.reLaunch({
               url: '/pages/tab-bar/authorization/authorization'
             });
           }, 1000);
         }
       }
     })
    } else {
      $wx.showToast('~ 已经是当前店铺啦 ~');
    }
  },

  /**
   * 获取扫码记录
   * @param params 参数
   *  @param p
   *  @param num
   *  @param name
   * @param upwardPull 是否为上拉
   * */
  getScanKey(params = {}, upwardPull = false) {
    let _this = this, td = _this.data;
    wx.showNavigationBarLoading();
    AJAX.getScanKey(params, (status, data, msg) => {
      wx.hideNavigationBarLoading();
      if (status) {
        let scanRecord;
        if (upwardPull) scanRecord = td.scanRecord.concat(data.data);
        else scanRecord = data.data;

        _this.setData({
          scanRecord: scanRecord,
          scanRecordTotalPage: data.last_page,
          noRecord: scanRecord.length == 0 ? true : false
        });
      }else{
        $wx.showToast(msg);
        _this.setData({
          noRecord: true
        });
      }
    });
  }
});